<template>
  <AppLayout title="登录" :show-navbar="true" :show-back="false">
    <view class="login-container">
      <!-- Logo区域 -->
      <view class="logo-section">
        <image class="logo" src="/static/logo.png" mode="aspectFit" />
        <text class="app-name">家校合作平台</text>
        <text class="app-desc">连接学校与家庭的桥梁</text>
      </view>

      <!-- 登录表单 -->
      <view class="login-form">
        <view class="form-group">
          <text class="form-label">用户名</text>
          <input
            :value="formData.username"
            type="text"
            placeholder="请输入用户名"
            class="form-input"
            :disabled="loading"
            @input="onUsernameInput"
          />
          <text v-if="errors.username" class="form-error">{{ errors.username }}</text>
        </view>

        <view class="form-group">
          <text class="form-label">密码</text>
          <input
            :value="formData.password"
            type="password"
            placeholder="请输入密码"
            class="form-input"
            :disabled="loading"
            :password="true"
            secure-text-entry
            @input="onPasswordInput"
          />
          <text v-if="errors.password" class="form-error">{{ errors.password }}</text>
        </view>

        <!-- 记住密码和快速登录 -->
        <view class="form-options">
          <checkbox-group @change="onRememberPasswordChange">
            <label class="remember-password">
              <checkbox
                :checked="formData.rememberPassword"
                color="#007AFF"
              />
              <text class="remember-text">记住密码</text>
            </label>
          </checkbox-group>
          <text class="quick-login-link" @click="toggleSavedAccounts">快速登录</text>
        </view>

        <!-- 保存的账号列表 -->
        <view v-if="showSavedAccounts && savedAccounts.length > 0" class="saved-accounts">
          <text class="saved-accounts-title">选择账号：</text>
          <view class="account-list">
            <view
              v-for="(account, index) in savedAccounts"
              :key="index"
              class="account-item"
              @tap="selectSavedAccount(account, index)"
              hover-class="account-item-hover"
            >
              <view class="account-info">
                <text class="account-username">{{ account.realName || account.username }}</text>
                <text class="account-detail">{{ account.username }}</text>
                <text v-if="account.lastLoginTime" class="account-time">
                  上次登录: {{ formatLoginTime(account.lastLoginTime) }}
                </text>
              </view>
              <view class="account-actions">
                <text v-if="account.password" class="has-password-icon">🔑</text>
                <text
                  class="remove-account"
                  @click.stop="removeSavedAccount(index)"
                >
                  ✕
                </text>
              </view>
            </view>
          </view>
        </view>

        <!-- 登录按钮 -->
        <FormButton
          :text="loading ? '登录中...' : '登录'"
          type="primary"
          size="large"
          :loading="loading"
          :disabled="!canLogin"
          block
          @click="handleLogin"
        />
      </view>
    </view>

    <!-- 全屏加载 -->
    <AppLoading
      v-if="globalLoading"
      type="fullscreen"
      text="登录中..."
    />
  </AppLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { authActions, authGetters } from '@/store/modules/auth'
import { UserRole } from '@/utils/auth'
import { navigateAfterLogin } from '@/utils/navigation'
import { roleUtils } from '@/api/auth'
import AppLayout from '@/components/common/AppLayout.vue'
import FormButton from '@/components/common/FormButton.vue'
import AppLoading from '@/components/common/AppLoading.vue'

// 响应式数据
const loading = ref(false)
const globalLoading = ref(false)
const showSavedAccounts = ref(false)

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  rememberPassword: false
})

// 保存的账号列表
const savedAccounts = ref<Array<{
  username: string
  password?: string
  realName?: string
  lastLoginTime?: string
}>>([])

// 当前选中的保存账号索引
const selectedAccountIndex = ref(-1)

// 表单验证错误
const errors = reactive({
  username: '',
  password: ''
})

// 输入处理方法
const onUsernameInput = (e: any) => {
  formData.username = e.detail.value
  clearErrors()
}

const onPasswordInput = (e: any) => {
  formData.password = e.detail.value
  clearErrors()
}

const onRememberPasswordChange = (e: any) => {
  // 使用checkbox-group时，e.detail.value是选中的值的数组
  formData.rememberPassword = e.detail.value.length > 0
  console.log('记住密码状态变更:', formData.rememberPassword, '事件数据:', e.detail.value)
}

const toggleSavedAccounts = () => {
  const newValue = !showSavedAccounts.value
  showSavedAccounts.value = newValue
  console.log('切换账号列表显示:', newValue)
  console.log('当前保存的账号数量:', savedAccounts.value.length)

  if (newValue && savedAccounts.value.length === 0) {
    uni.showToast({
      title: '暂无保存的账号',
      icon: 'none',
      duration: 1500
    })
  }
}

const formatLoginTime = (time: string) => {
  try {
    const date = new Date(time)
    const now = new Date()
    const diff = now.getTime() - date.getTime()

    if (diff < 60 * 1000) {
      return '刚刚'
    } else if (diff < 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 1000))}分钟前`
    } else if (diff < 24 * 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
    } else {
      return date.toLocaleDateString()
    }
  } catch {
    return '未知时间'
  }
}

// 计算属性
const canLogin = computed(() => {
  return formData.username.trim() !== '' &&
         formData.password.trim() !== '' &&
         !Object.values(errors).some(error => error !== '')
})

// 生命周期
onMounted(() => {
  // 如果已登录，跳转到对应页面
  if (authGetters.isAuthenticated.value) {
    navigateAfterLogin(authGetters.currentRole.value || '')
  }

  // 尝试从本地存储恢复表单数据
  restoreFormData()
})

/**
 * 清除错误信息
 */
const clearErrors = () => {
  errors.username = ''
  errors.password = ''
}

/**
 * 验证表单
 */
const validateForm = (): boolean => {
  clearErrors()

  let isValid = true

  // 用户名验证
  if (!formData.username.trim()) {
    errors.username = '请输入用户名'
    isValid = false
  } else if (formData.username.length < 3) {
    errors.username = '用户名至少3个字符'
    isValid = false
  } else if (!/^[a-zA-Z0-9_]+$/.test(formData.username)) {
    errors.username = '用户名只能包含字母、数字和下划线'
    isValid = false
  }

  // 密码验证
  if (!formData.password.trim()) {
    errors.password = '请输入密码'
    isValid = false
  } else if (formData.password.length < 6) {
    errors.password = '密码至少6个字符'
    isValid = false
  }

  return isValid
}

/**
 * 保存表单数据到本地存储
 */
const saveFormData = () => {
  try {
    const dataToSave: any = {
      username: formData.username,
      rememberPassword: formData.rememberPassword
    }

    // 如果选择记住密码，保存密码（注意：实际生产环境中应该加密存储）
    if (formData.rememberPassword) {
      dataToSave.password = formData.password
    }

    uni.setStorageSync('loginFormData', JSON.stringify(dataToSave))
  } catch (error) {
    console.error('保存表单数据失败:', error)
  }
}

/**
 * 保存账号到历史记录
 */
const saveAccountToHistory = (userInfo: any) => {
  try {
    console.log('保存账号到历史记录, 用户信息:', userInfo)
    console.log('记住密码状态:', formData.rememberPassword)

    const existingIndex = savedAccounts.value.findIndex(acc => acc.username === formData.username)

    const accountData = {
      username: formData.username,
      realName: userInfo.realName || formData.username,
      lastLoginTime: new Date().toISOString(),
      password: formData.rememberPassword ? formData.password : undefined
    }

    console.log('准备保存的账号数据:', {
      ...accountData,
      password: accountData.password ? '***' : '(未保存)'
    })

    if (existingIndex >= 0) {
      // 更新现有账号
      savedAccounts.value[existingIndex] = accountData
      console.log('更新现有账号，索引:', existingIndex)
    } else {
      // 添加新账号，最多保存5个
      savedAccounts.value.unshift(accountData)
      if (savedAccounts.value.length > 5) {
        savedAccounts.value = savedAccounts.value.slice(0, 5)
      }
      console.log('添加新账号到历史记录')
    }

    console.log('保存后的账号列表数量:', savedAccounts.value.length)
    uni.setStorageSync('savedAccounts', JSON.stringify(savedAccounts.value))
    console.log('账号数据已保存到本地存储')
  } catch (error) {
    console.error('保存账号历史失败:', error)
  }
}

/**
 * 选择保存的账号
 */
const selectSavedAccount = (account: any, index: number) => {
  console.log('选择账号:', account)
  console.log('账号索引:', index)

  formData.username = account.username
  if (account.password) {
    formData.password = account.password
    formData.rememberPassword = true
    console.log('已填充密码')
  } else {
    formData.password = ''
    formData.rememberPassword = false
    console.log('未保存密码，清空密码字段')
  }

  selectedAccountIndex.value = index
  showSavedAccounts.value = false
  clearErrors()

  console.log('表单数据更新后:', {
    username: formData.username,
    password: formData.password ? '***' : '(空)',
    rememberPassword: formData.rememberPassword
  })

  uni.showToast({
    title: `已选择 ${account.realName || account.username}`,
    icon: 'success',
    duration: 1500
  })
}

/**
 * 删除保存的账号
 */
const removeSavedAccount = (index: number) => {
  savedAccounts.value.splice(index, 1)
  uni.setStorageSync('savedAccounts', JSON.stringify(savedAccounts.value))

  // 如果删除的是当前选中的账号，重置选择
  if (selectedAccountIndex.value === index) {
    selectedAccountIndex.value = -1
  }
}

/**
 * 从本地存储恢复表单数据
 */
const restoreFormData = () => {
  try {
    // 恢复保存的账号列表
    const accountsData = uni.getStorageSync('savedAccounts')
    console.log('原始账号数据:', accountsData)

    if (accountsData) {
      savedAccounts.value = JSON.parse(accountsData)
      console.log('恢复的账号列表:', savedAccounts.value)
    } else {
      console.log('没有找到保存的账号数据')
    }

    // 恢复当前表单数据
    const savedData = uni.getStorageSync('loginFormData')
    console.log('原始表单数据:', savedData)

    if (savedData) {
      const data = JSON.parse(savedData)
      formData.username = data.username || ''
      formData.rememberPassword = data.rememberPassword || false

      // 如果记住密码，恢复密码
      if (formData.rememberPassword && data.password) {
        formData.password = data.password
      }

      console.log('恢复的表单数据:', {
        username: formData.username,
        password: formData.password ? '***' : '(空)',
        rememberPassword: formData.rememberPassword
      })
    } else {
      console.log('没有找到保存的表单数据')
    }
  } catch (error) {
    console.error('恢复表单数据失败:', error)
  }
}

/**
 * 处理登录
 */
const handleLogin = async () => {
  if (!validateForm()) return

  loading.value = true
  globalLoading.value = true

  const credentials = {
    username: formData.username.trim(),
    password: formData.password.trim()
  }

  console.log('开始登录，用户名:', credentials.username)

  const success = await authActions.login(credentials)

  if (success) {
    console.log('登录成功，准备跳转')

    // 保存当前登录的账号信息
    const currentUserInfo = authGetters.currentUser.value
    if (currentUserInfo) {
      saveAccountToHistory(currentUserInfo)
      saveFormData()
    }

    // 延迟跳转，让用户看到成功提示（authActions.login已经显示了成功提示）
    setTimeout(async () => {
      const userRole = authGetters.currentRole.value
      console.log('当前用户角色:', userRole)
      if (userRole) {
        await navigateAfterLogin(userRole)
      }
    }, 1000)
  } else {
    console.log('登录失败')
  }

  loading.value = false
  globalLoading.value = false
}

/**
 * 清除登录表单缓存
 */
const clearLoginFormCache = () => {
  try {
    uni.removeStorageSync('loginFormData')
  } catch (error) {
    console.error('清除登录表单缓存失败:', error)
  }
}

</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 40px 20px;
}

.logo-section {
  text-align: center;
  margin-bottom: 60px;

  .logo {
    width: 120px;
    height: 120px;
    margin-bottom: 20px;
    border-radius: 20px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  }

  .app-name {
    display: block;
    color: white;
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 8px;
  }

  .app-desc {
    display: block;
    color: rgba(255, 255, 255, 0.8);
    font-size: 16px;
  }
}

.login-form {
  background: white;
  border-radius: 20px;
  padding: 40px 30px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
}

.form-group {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.form-input {
  width: 100%;
  height: 48px;
  padding: 0 16px;
  border: 2px solid #e1e8ed;
  border-radius: 12px;
  font-size: 16px;
  color: #333;
  background: #fff;
  transition: all 0.3s ease;
  box-sizing: border-box;

  &:focus {
    border-color: #667eea;
    outline: none;
    box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
  }

  &:disabled {
    background: #f8f9fa;
    color: #999;
    cursor: not-allowed;
  }

  &::placeholder {
    color: #999;
  }
}

.form-error {
  display: block;
  font-size: 12px;
  color: #ff4757;
  margin-top: 4px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.remember-password {
  display: flex;
  align-items: center;
  gap: 8px;
}

.remember-text {
  font-size: 14px;
  color: #666;
}

.quick-login-link {
  font-size: 14px;
  color: #007AFF;
  text-decoration: underline;
  cursor: pointer;
}

.saved-accounts {
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e1e8ed;
}

.saved-accounts-title {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.account-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.account-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e1e8ed;
  cursor: pointer;
  transition: all 0.2s ease;
}

.account-item-hover {
  background: #f0f9ff;
  border-color: #007AFF;
}

.account-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.account-username {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.account-detail {
  font-size: 14px;
  color: #666;
}

.account-time {
  font-size: 12px;
  color: #999;
}

.account-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.has-password-icon {
  font-size: 16px;
}

.remove-account {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ff4757;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  cursor: pointer;
  transition: background 0.2s ease;

  &:hover {
    background: #ff3838;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .login-container {
    padding: 20px 16px;
  }

  .login-form {
    padding: 30px 20px;
  }


  .logo-section {
    margin-bottom: 40px;

    .logo {
      width: 100px;
      height: 100px;
    }

    .app-name {
      font-size: 24px;
    }
  }
}

// 动画增强
.login-form {
  animation: slideUp 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

.logo-section {
  animation: fadeIn 0.8s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
